import { base, toast } from 'nc-lightapp-front';
import presetVar from './presetVar';
const { NCRadio, NCCheckbox } = base;
import requestApi from './requestApi';

function tplHandle(meta) {


    this.checkboxOnchange = async (isleaf, pointPk, val) => {
        let manualPointStatus = this.state.manualPointStatus;

        let pointPksForProblem = [];
        let setSubLeafPointCheck = (rootChildren) => {
            rootChildren.forEach((pointPk) => {
                let childPoint = manualPointStatus[pointPk];
                if (!childPoint.isleaf) {
                    setSubLeafPointCheck(childPoint.children);
                } else {

                    let oldIsPass = childPoint.ispass;
                    //1、当前要点的oldIsPass是N时（说明当前操作为Y或null），才去该要点需要被减去的内容
                    //2、当前值为N，需要增加问题或增加问题的重复数量。
                    /* if (oldIsPass == 'N' || val == 'N') {
                        pointPksForProblem.push(pointPk);
                    } */

                    //1. 从不通过到通过时
                    //2. 从通过到不通过时。 
                    //Y和null用 非N表示
                    if ((oldIsPass == 'N' && val != "N") || (oldIsPass != 'N' && val == 'N')) {
                        pointPksForProblem.push(pointPk);
                    }
                    childPoint.ispass = val;
                }
            })
        }

        let currentPoint = null;

        if (isleaf) {
            currentPoint = manualPointStatus[pointPk];
            let oldIsPass = currentPoint.ispass;
            /* if (oldIsPass == 'N' || val == "N") {
                pointPksForProblem.push(pointPk);
            } */
            //1. 从不通过到通过时
            //2. 从通过到不通过时
            //Y和null用 非N表示
            if ((oldIsPass == 'N' && val != 'N') || (oldIsPass != 'N' && val == 'N')) {
                pointPksForProblem.push(pointPk);
            }
            currentPoint.ispass = val;
        } else {
            let rootChildren = null;
            if (pointPk == 'ALL') { //点击顶部的全选
                rootChildren = Object.keys(manualPointStatus);
            } else {
                rootChildren = manualPointStatus[pointPk].children;
            }
            setSubLeafPointCheck(rootChildren);
        }

        //问题处理 START
        let problemList = this.state.problemList;;
        if (pointPksForProblem.length) {
            let problemsData = await requestApi.problemQueryByPoint({
                pk_points: pointPksForProblem
            })
            problemsData.data.problems.forEach((item) => {
                let id = item.id;
                let problem = problemList[id];
                switch (val) {
                    case 'Y': //通过减掉对应的问题
                    case 'null':
                        if (problem) {
                            if (problem.execute_mode != 1) { //仅考虑手动问题
                                problem.repeatCount -= item.pagecount;
                                if (problem.repeatCount < 0) { //当重复值小于0时，删除问题
                                    delete problemList[id];
                                }
                            }
                        }

                        break;
                    case 'N': //增加不通过节点对应的问题
                        if (problem) {
                            if (problem.execute_mode != 1) {
                                problem.repeatCount += item.pagecount;
                            }
                        } else { //问题不存在时，新建问题
                            item.repeatCount = item.pagecount - 1;
                            problemList[id] = item;
                        }
                        break;
                }

            })
        }
        //问题处理 END

        //计算各层节点的checkbox状态
        calcCheck(manualPointStatus);
        //渲染
        this.setState({
            manualPointStatus,
            problemList
        })

    }

    let tplTable = {
        "items": [
            {
                label: this.state.comMultiLang['1056SideBar-010'], //1056SideBar-010 手工核查
                width: '200px',
                attrcode: "refname",
                itemtype: "label",
                visible: true,
                render: function (text, record, index) {
                    return <span className="firstcol-vertical" title={record.values.refname.value}>{record.values.refname.value}</span>;
                }

            },
            {
                label: '', //通过 不通过
                width: '190px',
                fixed: 'right',
                itemtype: "label",
                attrcode: "ispass",
                render: (_, record) => {
                    let pointPk = record.values.refpk.value;
                    let pointStatus = this.state.manualPointStatus[pointPk];
                    if (!pointStatus) {
                        console.error('gy:' + pointPk + '未在manualPointStatus中找到', this.state.manualPointStatus)
                        return null
                    }
                    if (record.isleaf) { //叶子节点
                        let isPass = pointStatus && pointStatus.ispass;
                        return (
                            this.props.isEdit ?
                                <div className="point-checkbox-wrap">
                                    <NCCheckbox
                                        className="first-checkbox point-checkbox"
                                        onChange={(isChecked) => {
                                            this.checkboxOnchange(true, pointPk, isChecked ? 'Y' : 'null');
                                        }}
                                        checked={isPass == 'Y'}
                                    ></NCCheckbox>

                                    <NCCheckbox
                                        className="point-checkbox"
                                        onChange={(isChecked) => {
                                            this.checkboxOnchange(true, pointPk, isChecked ? 'N' : 'null');

                                        }}
                                        checked={isPass == 'N'}
                                    >

                                    </NCCheckbox>
                                </div>
                                :
                                <div style={{ textAlign: 'right' }}>
                                    <i className='auto-point-pass ssc_audit_bar_iconfont icontongguo' style={{ display: isPass == 'Y' ? 'block' : 'none' }}></i>
                                    <i className='auto-point-unpass ssc_audit_bar_iconfont iconbutongguo' style={{ display: isPass == 'N' ? 'block' : 'none' }}></i>
                                </div>

                        );
                    } else { //非叶子节点
                        let leftParams = {};
                        let rightParams = {};
                        if (this.props.isEdit) {
                            if (pointStatus.fullChecked) { //全通过
                                leftParams.checked = true;
                                rightParams.checked = false;
                                leftParams.indeterminate = null;
                                rightParams.indeterminate = null;
                            } else { //不通过 或 半选
                                if (pointStatus.mayHalf) { //半选
                                    leftParams.checked = null;
                                    leftParams.indeterminate = true;
                                    rightParams.checked = null;
                                    if (pointStatus.haveN) {
                                        rightParams.indeterminate = true;
                                    } else {
                                        rightParams.indeterminate = false;
                                    }
                                } else { //不通过
                                    leftParams.checked = false;
                                    leftParams.indeterminate = null;
                                    rightParams.indeterminate = null;
                                    rightParams.checked = null;
                                    if (pointStatus.haveN) {
                                        if (pointStatus.haveNull) {
                                            rightParams.indeterminate = true;
                                        } else {
                                            rightParams.checked = true;
                                        }
                                    }
                                }
                            }
                        }

                        return (
                            this.props.isEdit ?
                                <div className="point-checkbox-wrap">
                                    <NCCheckbox
                                        className="first-checkbox point-checkbox"
                                        onChange={(isChecked) => {
                                            this.checkboxOnchange(false, pointPk, isChecked ? 'Y' : 'null');
                                        }}
                                        {...leftParams}
                                    ></NCCheckbox>

                                    <NCCheckbox
                                        className="point-checkbox"
                                        onChange={(isChecked) => {
                                            this.checkboxOnchange(false, pointPk, isChecked ? 'N' : 'null');

                                        }}
                                        {...rightParams}
                                    >
                                    </NCCheckbox>
                                </div>
                                :
                                null
                        )
                    }

                },
                visible: true
            }
        ],
        moduletype: "table",
        pagination: false,
        status: 'edit'
    }

    let autoPointTreeTpl = {
        "items": [
            {
                label: this.state.comMultiLang['1056SideBar-011'], //1056SideBar-011 自动审核内容
                width: '200px',
                attrcode: "refname",
                itemtype: "label",
                visible: true,
                render: function (text, record, index) {
                    return <span className="firstcol-vertical" title={record.values.refname.value}>{record.values.refname.value}</span>;
                }
            },
            {
                label: '',
                width: '190px',
                fixed: 'right',
                itemtype: "label",
                attrcode: "ispass",
                render: (_, record) => {
                    if (record.isleaf) {
                        let isPass = record.values.ispass.value;
                        return (
                            <div style={{ textAlign: 'right' }}>
                                <i className='auto-point-pass ssc_audit_bar_iconfont icontongguo' style={{ display: isPass == 'Y' ? 'block' : 'none' }}>  </i>
                                <i className='auto-point-unpass ssc_audit_bar_iconfont iconbutongguo' style={{ display: isPass == 'N' ? 'block' : 'none' }}>  </i>
                            </div>
                        );
                    } else {
                        return null;
                    }

                },
                visible: true
            }
        ],
        moduletype: "table",
        pagination: false,
        status: 'edit'
    }

    meta[presetVar.manualPointTree] = tplTable;
    meta[presetVar.autoPointTree] = autoPointTreeTpl;


}

//仅在初始化 或 刷新的时候调用
/**
 * 
 * @param {*} reqParam  请求参数   resetData时，reqParam参数为null
 * @param {*} isRefresh 是否刷新
 * @param {*} originData 是否存在缓存数据
 * @param {*} noRefreshShowToast 不展示刷新提示（我的作业iframe里单据保存时，自动执行刷新，不需要提示）
 */
async function setPointTreeData(reqParam, isRefresh, originData, noRefreshShowToast) {
    if (reqParam) {//resetData时，reqParam参数为null。 刷新时，需要用this.baseReqParam
        this.baseReqParam = reqParam; //刷新按钮事件需要用到这个参数
    }
    /* {
        billid:"1001ZG10000000004EZR",
        pk_task:"1001ZG10000000004F0C"
    } */
    let queryData = null;
    if (originData) { //取消编辑，重置数据时， 如单据稽核。
        queryData = originData;
    } else if (!isRefresh) { //非刷新
        queryData = await requestApi.auditDataQuery(reqParam, this.props.queryUrl);
    } else { //点击刷新按钮

        let userJson = {}
        if (reqParam.userjson) {
            userJson = JSON.parse(reqParam.userjson);
        }
        userJson = {
            ...userJson,
            ...getAuditData.call(this) //侧边栏数据
        }
        reqParam.userjson = JSON.stringify(userJson);
        queryData = await requestApi.refresh(reqParam);
        !noRefreshShowToast && toast({ title: this.state.comMultiLang['105601GGZD-0066'] }) /* 105601GGZD-0066 刷新成功 */
    }

    let pointShow = queryData.data.pointshow;
    let problemsshow = queryData.data.problemsshow;
    let hideRightBar = false;
    //notJudgeBarHide 为true时，不需要控制显示状态，如单据稽核
    if (!pointShow && !problemsshow && !this.props.notJudgeBarHide) { //为false时，判断problemsshow是否为false。
        hideRightBar = true; //隐藏右边栏
    }
    this.setState({
        hideRightBar,
        hideIframe: false //用来解决两个风车的问题
    })

    //联查场景使用的侧边栏，只有问题区域。且问题数据与其他场景数据结构不同
    if (this.props.scene == 'LinkQuery') {
        this.setState({
            problemList: queryData.data
        })
        return;
    }

    //数据兼容
    let pointsData = queryData.data.points;
    pointsData.sgtree || (pointsData.sgtree = {});
    pointsData.sgtree.nodes || (pointsData.sgtree.nodes = [])
    pointsData.zdtree || (pointsData.zdtree = {});
    pointsData.zdtree.nodes || (pointsData.zdtree.nodes = [])

    this.originData = queryData; //取消标记，重置数据时用，如单据稽核

    try {
        this.pk_comparison_result = queryData.data.pk_comparison_result; //佳佳接口用到该参数
        this._sscunitPK = queryData.data.sscunit.pk_unit; //问题参照用到该参数
    } catch (e) {
        console.error(e);
    }


    let { manualPointTree, autoPointTree } = await auditDataHandle.call(this, queryData);

    let newdata = this.props.treeTableManyCol.createNewData(manualPointTree.length ? manualPointTree : null);
    this.props.treeTableManyCol.initTreeTableData(presetVar.manualPointTree, newdata || [], 'refpk', true);

    this.adjustAllCheckWrapRightPadding();

    if (!this.props.disabledAutoPointTree) {
        let newdata2 = this.props.treeTableManyCol.createNewData(autoPointTree.length ? autoPointTree : null);
        this.props.treeTableManyCol.initTreeTableData(presetVar.autoPointTree, newdata2 || [], 'refpk', true);
    }

}

function calcCheck(manualPointRelationJson) {
    //判断根节点是否选中
    let judgeNestRootIsPass = (rootPoint) => {
        let factor = true; //初始值为true，但只要有没通过的，factor就为false
        rootPoint.haveNull = false;
        rootPoint.haveN = false;
        rootPoint.children.forEach((key) => {
            let item = manualPointRelationJson[key];
            if (!item.isleaf) {
                let result = judgeNestRootIsPass(item);
                if (result) {
                    rootPoint.mayHalf = true; //只要有通过的，半选参考就是true
                } else {
                    factor = false;
                }
            } else {
                if (item.ispass == 'Y') {
                    rootPoint.mayHalf = true; //只要有通过的，半选参考就是true
                } else {
                    factor = false;
                    if (item.ispass == 'null') {
                        rootPoint.haveNull = true;
                    }
                    if (item.ispass == 'N') {
                        rootPoint.haveN = true;
                    }
                }
            }
        })
        return factor;
    }

    for (let key in manualPointRelationJson) {
        if (!manualPointRelationJson[key].isleaf) {
            manualPointRelationJson[key].mayHalf = false;
            let checkResult = judgeNestRootIsPass(manualPointRelationJson[key]);
            manualPointRelationJson[key].fullChecked = checkResult;
        }
    }
}


//数据处理
function auditDataHandle(data) {

    let manualPointStatus = {};
    let problemList = {};

    //手动要点树的数据格式，仅setPointTreeData方法被调用的时候设置一次。后续通过manualPointStatus维护树上要点的通过状态
    let manualPointTree = [];
    //自动要点树的数据格式
    let autoPointTree = [];

    let { data: { points: { sgtree, zdtree }, problems, rectify_desc } } = data;

    //判断要点树复选框选中状态
    this.manualPointRelationJson = {};

    manualPointTree = sgtree.nodes.map((item) => {

        //树已经check的数据 start
        let newItem = manualPointStatus[item.refpk];
        if (!newItem) {
            manualPointStatus[item.refpk] = newItem = { pid: item.pid, isleaf: item.isleaf }
            if (!item.isleaf) {
                newItem.children = [];
            } else {
                newItem.ispass = item.ispass;
            }
        } else {
            newItem.pid = item.pid;
            newItem.isleaf = item.isleaf;
        }

        let parentItem = manualPointStatus[item.pid];
        if (item.pid != '') {
            if (!parentItem) {
                manualPointStatus[item.pid] = parentItem = { children: [item.refpk], pid: null }
            } else {
                manualPointStatus[item.pid].children.push(item.refpk);
            }
        }
        //树已经check的数据 end

        return {
            status: 0,
            isleaf: item.isleaf,
            values: {
                refpk: {
                    value: item.refpk
                },
                refname: {
                    value: item.refname
                },
                pid: {
                    value: item.pid
                },
                ispass: {
                    value: item.ispass
                },
                values: item.values
            }
        }
    });

    calcCheck.call(this, manualPointStatus);

    autoPointTree = zdtree.nodes.map((item) => {
        return {
            status: 0,
            isleaf: item.isleaf,
            values: {
                refpk: {
                    value: item.refpk
                },
                refname: {
                    value: item.refname
                },
                pid: {
                    value: item.pid
                },
                ispass: {
                    value: item.ispass
                },
                values: item.values
            }
        }
    })

    problems.forEach((item) => {
        if (item.execute_mode != 1) {
            item.repeatCount = item.pagecount - 1;  //查询时，pagecount为问题关联的要点数量。 repeatcount为重复的次数，需要减去1
        }
        problemList[item.id] = item;
    })

    this.autoPointTree = autoPointTree; //生成提交数据时会用


    return new Promise((resolve, _) => {
        this.setState({
            rectify_desc, //单据整改内容描述
            manualPointStatus,
            problemList
        }, () => {
            resolve({
                manualPointTree,
                autoPointTree,
                problems
            })
        })
    })
}


//生成提交数据 
function getAuditData(hasAuto) {
    let { problemList, manualPointStatus } = this.state;
    let problemArr = [];
    let pointArr = [];
    let autoPointArr = null;

    for (let key in manualPointStatus) {
        let point = manualPointStatus[key];
        if (point.isleaf) {
            pointArr.push({
                pk_points: key,
                ispass: point.ispass
            })
        }
    }

    for (let key in problemList) {
        let problem = problemList[key];
        if (problem.execute_mode != 1) {
            problemArr.push(problem);
        }
    }

    let result = {
        pk_comparison_result: this.pk_comparison_result,
        problems: problemArr,
        points: pointArr

    }

    if (this.props.isShowRectify) {
        result.rectify_desc = this.state.rectify_desc;
    }

    if (hasAuto) {
        autoPointArr = [];
        this.autoPointTree.forEach((item) => {
            autoPointArr.push({
                pk_points: item.refpk,
                ispass: item.ispass
            })
        })
        result.autopoints = autoPointArr;

    }
    return result

}


export { tplHandle, setPointTreeData, getAuditData, auditDataHandle };